package club.emergency.wechat.dictionary.search.provider.impl;

import club.emergency.wechat.common.response.StatusCode;
import club.emergency.wechat.common.response.ResponseEntity;
import club.emergency.wechat.dictionary.search.DictionarySearch;
import club.emergency.wechat.model.dictionary.DictionaryChild;
import club.emergency.wechat.model.dictionary.DictionaryParent;
import club.emergency.wechat.persistence.dictionary.DictionaryChildMapper;
import club.emergency.wechat.persistence.dictionary.DictionaryParentMapper;
import club.emergency.wechat.redis.RedisOperation;
import club.emergency.wechat.redis.common.RedisKeyConstant;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Create with IntelliJ IDEA
 * Project Name: wechat
 * Package Name: club.emergency.wechat.dictionary.search.provider.impl
 * Date: 2018/11/26
 *
 * @author: 快乐的小菌菌
 * Description:
 */
@RestController
public class DictionarySearchImpl implements DictionarySearch {

    private DictionaryParentMapper dictionaryParentMapper;

    private DictionaryChildMapper dictionaryChildMapper;

    private RedisOperation redisOperation;

    public DictionarySearchImpl(
            DictionaryParentMapper dictionaryParentMapper,
            DictionaryChildMapper dictionaryChildMapper,
            RedisOperation redisOperation
    ) {
        this.dictionaryParentMapper = dictionaryParentMapper;
        this.dictionaryChildMapper = dictionaryChildMapper;
        this.redisOperation = redisOperation;
    }

    @Override
    public String flipListForParent() {
        List<DictionaryParent> dictionaryParents = dictionaryParentMapper.selectList(null);
        return ResponseEntity.ok(StatusCode.DB_SEARCH_OK, "父字典所有数据查询成功！", dictionaryParents);
    }

    @Override
    public String flipListByKeyName(@RequestParam("keyName") String keyName) {
        String key = RedisKeyConstant.DICTIONARY_CHILD + keyName;
        if (!redisOperation.hasKey(key)) {
            QueryWrapper<DictionaryChild> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("key_name", keyName);
            queryWrapper.orderByDesc("modify_time");
            List<DictionaryChild> dictionaryChildren = dictionaryChildMapper.selectList(queryWrapper);
            redisOperation.add(key, dictionaryChildren);
            return ResponseEntity.ok(StatusCode.DB_SEARCH_OK, "根据keyName查询子字典数据(从缓存中）成功！", dictionaryChildren);
        }
        List list = redisOperation.getList(key, DictionaryChild.class);
        return ResponseEntity.ok(StatusCode.DB_SEARCH_OK, "根据keyName查询子字典数据成功！", list);
    }

}
